package com.app.common;

import javafx.scene.web.WebEngine;

/**
 * @Author 56465
 * @Create 2024/7/30 11:49
 */
public class MoveMouseJS {
    public static void moveCursorToEnd(WebEngine webEngine) {
        System.out.println("moveCursorToEnd");
        // 使用JavaScript将光标移动到<h1>元素的末尾
        webEngine.executeScript("""
                function moveCursorToEnd() {
                    var h1 = document.querySelector('h1');
                    var range = document.createRange();
                    var sel = window.getSelection();
                    range.selectNodeContents(h1);
                    range.collapse(false);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
                moveCursorToEnd();
                """);
        System.out.println("moveCursorToEnd end");
    }

    /**
     * 生成 p 标签，并将光标移动到新创建的<p>标签的末尾
     * @param webEngine
     */
    public static void addClickEventListener(WebEngine webEngine) {
        // 使用JavaScript监听WebView的点击事件，并创建一个新的<p>标签
        webEngine.executeScript("function addClickEventListener() {"
                + "document.body.addEventListener('click', function(event) {"
                + "  var p = document.createElement('p');"
                + "  p.contentEditable = 'true';"
                + "  document.body.appendChild(p);"
                + "  var range = document.createRange();"
                + "  range.selectNodeContents(p);"
                + "  range.collapse(true);"
                + "  var sel = window.getSelection();"
                + "  sel.removeAllRanges();"
                + "  sel.addRange(range);"
                + "});"
                + "}"
                + "addClickEventListener();");
    }
    public static void test(WebEngine webEngine) {
        String jsScript = """
                function modifyParagraph() {
                            // 选择 p 标签
                            var p = document.getElementById("myParagraph");
                            // 获取 p 标签的内容
                            var content = p.innerHTML;
                            // 修改内容
                            var newContent = content + " 这是修改后的内容。";
                            // 设置新的内容
                            p.innerHTML = newContent;
                        };
                modifyParagraph();        
                """;
        webEngine.executeScript(jsScript);
    }
}
